#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "member.h"
#include "common.h"


#define MEMBER_INFO_FILE "data/member_info.dat"
#define MEMBER_ID_BASE 100001


void print_member_info(const member_info* mi);


static unsigned int get_new_mid(void)
{
	member_info mi;
	unsigned int mid;

	FILE *fp = fopen(MEMBER_INFO_FILE,"rb");

		if(fp == NULL)
		{
			return MEMBER_ID_BASE;
		}
	fseek(fp,-sizeof(mi),SEEK_END);

	if(fread(&mi,sizeof(mi),1,fp) == 1)
	{
		mid = mi.mid + 1;
	}
	else
	{
		mid = MEMBER_ID_BASE;
	}

	fclose(fp);

	return mid;

}

void member_reg(void)
{
	member_info mi;

	printf("请按照如下提升输入会员信息：\n");	
	printf("卡号：");
	scanf("%s",mi.card_num);

	printf("姓名：");
	scanf("%s",mi.name);

	printf("性别(1-女，2-男):");
	scanf("%d",(int*)&mi.s);

	printf("手机号:");
	scanf("%s",mi.phone);

	printf("会员类型(1-次卡，2-月卡，3-季卡，4-年卡):");
	scanf("%d",(int*)&mi.mt);

	if(mi.mt == cika)
	{
		printf("剩余次数:");
		scanf("%d",&mi.remain_cnt);
	}

	mi.regtime = time(NULL);

	if(mi.mt == yueka)
	{
		mi.expire_time = mi.regtime + 30*24*60*60;
	}
	else if(mi.mt == jika)
	{
		mi.expire_time = mi.regtime + 3*30*24*60*60;
	}
	else if(mi.mt == nianka)
	{
		 mi.expire_time = mi.regtime + 365*24*60*60;

	}

	mi.mid = get_new_mid();
	mi.delete_state = 0;

	FILE* fp = fopen(MEMBER_INFO_FILE,"ab");

	if(fp == NULL)
	{
		perror("会员注册失败！");
		return;
	}

	fwrite(&mi,sizeof(mi),1,fp);

	fclose(fp);

	printf("会员注册成功!\n");
}

void member_show(void)
{
	member_info mi;
	char card_num[11];

	system("clear");//清屏

	printf("\n会员请刷卡!\n");
	scanf("%s",card_num);
	getchar();

	system("clear");

	FILE* fp = fopen(MEMBER_INFO_FILE,"rb");

	if(fp == NULL)
	{
		printf("\n卡片未注册,请联系工作人员处理！\n");
		return;
	}
	
	while(fread(&mi,sizeof(mi),1,fp)==1)
	{
		if(strcmp(mi.card_num,card_num) == 0) break;
	}

	if(feof(fp))
	{
		printf("\n卡片未注册，请联系工作人员！\n");
	}
	else
	{
		if(mi.delete_state ==1) 
		{
			printf("\n次卡已注销，请联系工作人员处理！\n");
		}
		else
		{
			printf("\n尊贵的会员，您的信息如下:\n\n");
			print_member_info(&mi);
		}
	}

	fclose(fp);

	press_any_key();
    system("clear");
}


void member_del(void)
{

    // 首先进行密码验证
    if(!verify_admin_password())
    {
        return;  // 密码验证失败，直接返回
    }

	char num[50];
	member_info mi;

	printf("请输入要注销的会员的卡号/会员ID/手机号：");
	scanf("%s",num);
	getchar();

	FILE* fp = fopen(MEMBER_INFO_FILE,"r+");
	if(fp == NULL)
	{
		printf("无法打开会员数据文件！\n");
		return;
	}

	while(fread(&mi,sizeof(mi),1,fp) == 1)
	{
		if(strcmp(num,mi.card_num) == 0 || strcmp(num,mi.phone) == 0 || atol(num) == mi.mid)
		{
			break;
		}
	}

	if(feof(fp))
	{
		printf("\n不存在此会员，核销失败！\n");
	}
	else
	{
		char select;

		printf("\n要注销的会员信息如下：\n");
		{
			print_member_info(&mi);

			printf("是否要注销会员(Y/N)");
			select = getchar();

			if(select == 'Y' ||select == 'y')
			{
				mi.delete_state = 1;

				fseek(fp,-sizeof(mi),SEEK_CUR);

				fwrite(&mi,sizeof(mi),1,fp);

				printf("\n会员已注销!\n");
			}
		}

		fclose(fp);
	}
}	
void print_member_info(const member_info* mi)
{
	printf("卡号：%s\n",mi->card_num);
	printf("会员ID:%u\n",mi->mid);
	printf("姓名：%s\n",mi->name);
	printf("性别：%s\n",mi->s == female ? "女":"男");
	printf("手机号：%s\n",mi->phone);

	printf("会员类型：");
	if(mi->mt == cika)
	{
		printf("次卡\n剩余次数：%d\n", mi->remain_cnt);
	}
	else if(mi->mt == yueka)
	{
		printf("月卡\n");
	}
	else if(mi->mt == jika)
	{
		printf("季卡\n");	
	}

	else if(mi->mt == nianka)
	{
		printf("年卡\n");	
	}

	struct tm* dt;

	dt = localtime(&mi->expire_time);

	printf("到期时间：%d年%d月%d日 %02d:%02d\n", dt->tm_year + 1900, dt->tm_mon + 1, dt->tm_mday, dt->tm_hour, dt->tm_min);

	dt = localtime(&mi->regtime);

	printf("注册时间：%d年%d月%d日 %02d:%02d\n", dt->tm_year + 1900, dt->tm_mon + 1, dt->tm_mday, dt->tm_hour, dt->tm_min);
}



// 管理员模式: 查看所有会员 
void member_list_all(void)
{
    // 首先进行密码验证
    if(!verify_admin_password())
    {
        return;  // 密码验证失败，直接返回
    }

    //等待用户按回车键继续
    printf("认证成功！按回车键查看会员列表...");
    getchar();  // 等待用户按回车
    system("clear");

    member_info mi;
    int count = 0;
    
    // 标题
    printf("\n\n                    所有会员列表\n\n");
    
    FILE* fp = fopen(MEMBER_INFO_FILE, "rb");
    if(fp == NULL)
    {
        printf("暂无会员数据！\n");
        press_any_key();
        return;
    }
    
    // 读取并显示会员信息
    while(fread(&mi, sizeof(mi), 1, fp) == 1)
    {
        char* type_str = "";
        switch(mi.mt)
        {
            case cika: type_str = "次卡"; break;
            case yueka: type_str = "月卡"; break;
            case jika: type_str = "季卡"; break;
            case nianka: type_str = "年卡"; break;
        }
        
        char* status_str = (mi.delete_state == 1) ? "已注销" : "正常";
        
        // 显示会员信息，不使用表格格式
        printf("会员ID: %u\n", mi.mid);
        printf("卡号: %s\n", mi.card_num);
        printf("姓名: %s\n", mi.name);
        printf("手机号: %s\n", mi.phone);
        printf("类型: %s\n", type_str);
        printf("状态: %s\n", status_str);
        
        // 在每条记录之间添加分隔线
        printf("----------------------------------------\n");
        
        count++;
    }
    
    fclose(fp);
    
    printf("\n总计: %d 个会员\n", count);
    press_any_key();
    system("clear");
}


// 管理员密码验证函数  
int verify_admin_password(void)
{
    char password[50];
    int attempts = 3;  // 最多尝试3次

    // 设置管理员密码，这里设为 "admin123"，您可以修改成其他密码
    const char* correct_password = "123456";

    while(attempts > 0)
    {
        printf("\n=== 管理员认证 ===\n");
        printf("请输入管理员密码 (剩余尝试次数: %d): ", attempts);

        // 隐藏密码输入
        system("stty -echo");  // 关闭回显
        scanf("%49s", password);
        system("stty echo");   // 恢复回显
        printf("\n");

        if(strcmp(password, correct_password) == 0)
        {
            printf("认证成功！欢迎管理员！\n");
            return 1;  // 验证成功
        }
        else
        {
            printf("密码错误！\n");
            attempts--;
        }
    }

    printf("认证失败，返回主菜单！\n");
    return 0;  // 验证失败
}

// 会员消费扣次功能
void member_consume(void)
{
    member_info mi;
    char card_num[11];

    system("clear");
    printf("\n=== 会员消费扣次 ===\n");
    printf("请刷卡或输入卡号：");
    scanf("%s", card_num);
    getchar();

    FILE* fp = fopen(MEMBER_INFO_FILE, "r+");
    if(fp == NULL)
    {
        printf("\n系统错误，无法打开会员数据文件！\n");
        press_any_key();
        system("clear");
        return;
    }

    long found_pos = -1;

    // 查找会员记录
    while(fread(&mi, sizeof(mi), 1, fp) == 1)
    {
        if(strcmp(mi.card_num, card_num) == 0 && mi.delete_state == 0)
        {
            found_pos = ftell(fp) - sizeof(mi);
            break;
        }
    }

    if(found_pos == -1)
    {
        printf("\n卡号不存在或会员已注销，请确认！\n");
        fclose(fp);
        press_any_key();
        system("clear");
        return;
    }

    // 显示会员信息
    printf("\n会员信息：\n");
    printf("卡号：%s\n", mi.card_num);
    printf("姓名：%s\n", mi.name);
    printf("会员类型：");

    switch(mi.mt)
    {
        case cika:
            printf("次卡\n");
            printf("当前剩余次数：%d\n", mi.remain_cnt);
            break;
        case yueka:
            printf("月卡\n");
            break;
        case jika:
            printf("季卡\n");
            break;
        case nianka:
            printf("年卡\n");
            break;
    }

    // 处理不同类型的会员
    if(mi.mt == cika)
    {
        // 次卡会员：扣减次数
        if(mi.remain_cnt <= 0)
        {
            printf("\n剩余次数不足，无法消费！\n");
        }
        else
        {
            char confirm;
            printf("\n确认消费一次？(Y/N): ");
            scanf("%c", &confirm);
            getchar();

            if(confirm == 'Y' || confirm == 'y')
            {
                mi.remain_cnt--;

                // 更新文件中的记录
                fseek(fp, found_pos, SEEK_SET);
                fwrite(&mi, sizeof(mi), 1, fp);

                printf("\n消费成功！剩余次数：%d\n", mi.remain_cnt);

                if(mi.remain_cnt == 0)
                {
                    printf("温馨提示：您的次数已用完，请及时充值！\n");
                }
            }
            else
            {
                printf("\n取消消费操作。\n");
            }
        }
    }
    else
    {
        // 其他类型会员：显示到期时间
        struct tm* dt = localtime(&mi.expire_time);
        printf("到期时间：%d年%d月%d日\n", dt->tm_year + 1900, dt->tm_mon + 1, dt->tm_mday);

        // 检查是否已过期
        time_t current_time = time(NULL);
        if(current_time > mi.expire_time)
        {
            printf("温馨提示：您的会员卡已过期！\n");
        }
        else
        {
            // 计算剩余天数
            int days_left = (mi.expire_time - current_time) / (24 * 60 * 60);
            printf("剩余有效期：%d天\n", days_left);
        }

        printf("\n欢迎光临！祝您玩得愉快！\n");
    }

    fclose(fp);
    press_any_key();
    system("clear");
}


// 修改会员信息功能（管理员权限）
void member_modify(void)
{
    // 首先进行密码验证
    if(!verify_admin_password())
    {
        return;  // 密码验证失败，直接返回
    }

    member_info mi;
    char num[50];
    long found_pos = -1;

    printf("请输入要修改会员的卡号/会员ID/手机号: ");
    scanf("%s", num);
    getchar();

    FILE* fp = fopen(MEMBER_INFO_FILE, "r+");
    if(fp == NULL)
    {
        printf("无法打开会员数据文件！\n");
        press_any_key();
        system("clear");
        return;
    }

    // 查找会员记录
    while(fread(&mi, sizeof(mi), 1, fp) == 1)
    {
        if(mi.delete_state == 0 &&
           (strcmp(num, mi.card_num) == 0 ||
            strcmp(num, mi.phone) == 0 ||
            atol(num) == mi.mid))
        {
            found_pos = ftell(fp) - sizeof(mi);
            break;
        }
    }

    if(found_pos == -1)
    {
        printf("\n会员不存在或已注销！\n");
        fclose(fp);
        press_any_key();
        system("clear");
        return;
    }

    int choice;
    int modified = 0; // 标记是否进行了修改
    
    do {
        // 显示当前会员信息
        system("clear");
        printf("\n=== 修改会员信息 ===\n");
        printf("当前会员信息：\n");
        print_member_info(&mi);
        
        printf("\n请选择要修改的信息：\n");
        printf("1. 姓名\n");
        printf("2. 手机号\n");
        printf("3. 会员类型\n");
        if(mi.mt == cika) {
            printf("4. 剩余次数\n");
        }
        printf("9. 保存并返回\n");
        printf("0. 取消修改\n");
        printf("请选择: ");
        scanf("%d", &choice);
        getchar();

        // 根据选择修改相应字段
        switch(choice)
        {
            case 1:
                printf("请输入新的姓名: ");
                scanf("%30s", mi.name);
                printf("姓名修改成功！\n");
                modified = 1;
                break;

            case 2:
                printf("请输入新的手机号: ");
                scanf("%11s", mi.phone);
                printf("手机号修改成功！\n");
                modified = 1;
                break;

            case 3:
                printf("请输入新的会员类型(1-次卡，2-月卡，3-季卡，4-年卡): ");
                scanf("%d", (int*)&mi.mt);

                // 如果改为次卡，需要输入剩余次数
                if(mi.mt == cika)
                {
                    printf("请输入剩余次数: ");
                    scanf("%d", &mi.remain_cnt);
                }

                // 重新计算到期时间
                time_t current_time = time(NULL);
                if(mi.mt == yueka)
                {
                    mi.expire_time = current_time + 30*24*60*60;
                }
                else if(mi.mt == jika)
                {
                    mi.expire_time = current_time + 3*30*24*60*60;
                }
                else if(mi.mt == nianka)
                {
                    mi.expire_time = current_time + 365*24*60*60;
                }
                printf("会员类型修改成功！\n");
                modified = 1;
                break;

            case 4:
                if(mi.mt == cika)
                {
                    printf("请输入新的剩余次数: ");
                    scanf("%d", &mi.remain_cnt);
                    printf("剩余次数修改成功！\n");
                    modified = 1;
                }
                else
                {
                    printf("只有次卡会员才能修改剩余次数！\n");
                }
                break;

            case 9:
                // 保存修改并退出
                if(modified)
                {
                    fseek(fp, found_pos, SEEK_SET);
                    if(fwrite(&mi, sizeof(mi), 1, fp) == 1)
                    {
                        printf("\n所有修改已保存成功！\n");
                    }
                    else
                    {
                        printf("\n保存修改失败！\n");
                    }
                }
                else
                {
                    printf("\n没有进行任何修改。\n");
                }
                fclose(fp);
                press_any_key();
                system("clear");
                return;

            case 0:
                printf("取消修改操作，所有未保存的修改将丢失。\n");
                fclose(fp);
                press_any_key();
                system("clear");
                return;

            default:
                printf("无效的选择！请重新选择。\n");
                press_any_key();
                break;
        }
        
        if(choice >= 1 && choice <= 4) {
            printf("按任意键继续修改...");
            getchar();
        }
    } while(1);
}
